//
//  WmcFontManager.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/7.
//

import Foundation
import UIKit
import YPBedrock

class WmcFontManager: NSObject {
    // Internal

    /// 单例实例化
    static let shared: WmcFontManager = {
        let manager = WmcFontManager()
        return manager
    }()

    /// 数码管斜体字名
    static var digitalFontItalicName: String = "Digital-7 Italic"

    /// 数码管字名
    static var digitalFontName: String = "Digital-7"

    /// 数字字体名
    static var dinAlternateFontName: String = "DINAlternate-Bold"

    /// 优设标题黑字体名
    static var youSheBiaoTiFontName: String = "YouSheBiaoTiHei"

    var registerQueue: DispatchQueue = .init(label: "wmc.queue.WmcFontManager")

    /// 数码管斜体
    static func digitalItalicFont(_ size: CGFloat) -> UIFont? {
        return UIFont(name: digitalFontItalicName, size: size)
    }

    /// 数码管体
    static func digitalFont(_ size: CGFloat) -> UIFont? {
        return UIFont(name: digitalFontName, size: size)
    }

    /// 数字字体
    static func dinAlternateFont(_ size: CGFloat) -> UIFont? {
        return UIFont(name: dinAlternateFontName, size: size)
    }

    /// 优设标题黑字体
    static func youSheBiaoTiFont(_ size: CGFloat) -> UIFont? {
        return UIFont(name: youSheBiaoTiFontName, size: size)
    }

    func config() {
        registerQueue.async { [weak self] in
            guard let weakSelf = self else { return }
            Self.digitalFontItalicName = weakSelf.loadFontFile("digital-7 (italic)")
            Self.digitalFontName = weakSelf.loadFontFile("digital-7")
            Self.youSheBiaoTiFontName = weakSelf.loadFontFile("YouSheBiaoTiHei")
        }
    }

    /// 动态注册字体
    func loadFontFile(_ name: String, ofType type: String = "ttf") -> String {
        guard let path = Bundle.WmcBundle.path(forResource: name, ofType: type) else {
            log("字体加载错误！\(name)")
            return ""
        }
        let fontData = NSData(contentsOfFile: path)
        // ...通过CGDataProvider承载生成CGFont对象
        let fontDataProvider = CGDataProvider(data: CFBridgingRetain(fontData) as! CFData)
        let fontRef = CGFont(fontDataProvider!)!
        // ...注册字体
        var fontError = Unmanaged<CFError>?.init(nilLiteral: ())
        CTFontManagerRegisterGraphicsFont(fontRef, &fontError)
        // ...获取了字体实际名字
        let fullName: String = fontRef.fullName! as String
        let postScriptName: String = fontRef.postScriptName! as String
        log("字体注册成功！\tFullName: \(fullName)\tPostScriptName: \(postScriptName)")
        return fullName
    }

    // Fileprivate

    /// 日志系统
    fileprivate func log(_ log: String) {
        WmcLogManager.DebugLog(type: .fontManager, log: log)
    }
}
